<template>
  <div class="reset-pwd q-gutter-y-sm q-px-lg">
    <div class="warning-tips text-grey-7 text-weight-medium row items-center no-wrap q-my-lg">
      <q-icon class="map-warning-tips-icon" name="mdi-information-variant" size="1.25rem"></q-icon>
      <div>{{ $t('ResetPwdTip1') }}</div>
    </div>
    <!-- 租户号 -->
    <q-input v-if="false" ref="tenInput" v-model="formInfo.tenantId" :loading="loading"
             :placeholder="`${$.t('TenantCode')}`" :readonly="loading"
             :rules="[ val => val && val.length > 0 || `${$t('PleaseInput')} ${$.t('TenantCode')}`]" dense lazy-rules
             outlined @keydown.enter="setKeyCode" @keyup.enter="login('Tenant')">
      <template v-slot:prepend>
        <q-icon name="group" />
      </template>
    </q-input>
    <!-- 用户名 -->
    <q-input ref="nameInput" v-model="formInfo.username" :loading="loading" :placeholder="`${$t('AccountTip1')}`"
             :readonly="loading" :rules="[val => val && val.length > 0 || `${$t('PleaseInput')} ${$t('AccountTip1')}`]"
             dense lazy-rules outlined @keydown.enter="setKeyCode" @keyup.enter="login('Input')">
      <template v-slot:prepend>
        <q-icon name="account_circle" />
      </template>
    </q-input>
    <!-- 密码 -->
    <q-input ref="codeInput" v-model="formInfo.authCode" :loading="loading" :placeholder="`${$t('AuthCode')}`"
             :readonly="loading" :rules="[val => codeVali(val)]" dense lazy-rules outlined @keydown.enter="setKeyCode"
             @keyup.enter="login('Code')">
      <template v-slot:prepend>
        <q-icon name="verified_user" />
      </template>
      <template v-slot:after>
        <div
          class="reset-pwd-box rounded-borders no-wrap row justify-center items-center cursor-pointer overflow-hidden"
          @click="contactStr"></div>
      </template>
    </q-input>

    <q-btn :loading="loading" class="bg-login-btn text-subtitle1 text-weight-bold full-width q-mb-xl" flat rounded
           text-color="white" @click="login">
      {{ `${$t('NextStep')}` }}
    </q-btn>
  </div>
</template>

<script setup>

import { postAPI } from 'src/api'
import { i18n } from 'boot/i18n'
import { inject, onMounted, ref } from 'vue'

defineProps({
  step: Number,
  username: String,
  captchaKey: String
})

const TENANT_ID = inject('TENANT_ID')
const emits = defineEmits(['update:step', 'update:username', 'update:captchaKey'])

const code = ref('')
const keyCode = ref(0)
const loading = ref(false)
const tenInput = ref(null)
const codeInput = ref(null)
const nameInput = ref(null)
const formInfo = ref({ captchType: 'MAIL', tenantId: TENANT_ID })

const codeVali = val => {
  if (!val) return `${i18n.t('PleaseInput')} ${i18n.t('AuthCode')}`
  if (val.toUpperCase() === code.value.toUpperCase()) return true
  return `${i18n.t('AuthCode')} ${i18n.t('VerifyTip1')}`
}

const setKeyCode = e => (keyCode.value = e.keyCode)

const login = keyType => {
  if (keyCode.value === 229) return // 中文输入法输入中文情况下 keydown.enter事件键值为229
  if (keyType === 'Input' && !nameInput.value.validate()) return nameInput.value.focus()
  if (keyType === 'Code' && !codeInput.value.validate()) return codeInput.value.focus()

  if (!nameInput.value.validate()) return nameInput.value.focus()
  if (!codeInput.value.validate()) return codeInput.value.focus()

  codeInput.value.blur()
  nameInput.value.blur()

  loading.value = !loading.value

  postAPI('/auth/api/captcha/sendVerificationCode', formInfo.value, data => {
    emits('update:step', 2)
    emits('update:captchaKey', data.captchaKey)
    emits('update:username', formInfo.value.username)
    loading.value = !loading.value
  }, () => {
    loading.value = !loading.value
    contactStr()
  })
}

onMounted(() => contactStr())

// 生成随机验证码
const contactStr = () => {
  const tempNode = codeInput.value.$el.querySelector('.reset-pwd-box')
  code.value = ''
  tempNode.innerHTML = ''
  let fontColor = ''
  let angle = ''
  let fontSize = ''
  let marginNum = ''
  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < 4; j++) {
      // 生成随机颜色
      const pro = Math.random()
      if (pro < 0.5) {
        fontColor += String.fromCharCode(Math.floor(Math.random() * 4) + 97)
      } else {
        fontColor += Math.floor(Math.random() * 10)
      }
    }
    // 生成随机角度
    angle = Math.random() < 0.5 ? -Math.random() * 20 - 25 : Math.random() * 20 + 25
    fontSize = Math.floor(Math.random() * 5) + 16 + 'px'
    marginNum = Math.floor(Math.random() * 3) + 'px'
    fontColor = `#${fontColor}CC`
    const spanEle = document.createElement('li')
    const probability = Math.random()
    if (probability <= 0.33) {
      spanEle.innerHTML += newChar('num')
    } else if (probability > 0.33 && probability <= 0.66) {
      spanEle.innerHTML += newChar('smallChar')
    } else {
      spanEle.innerHTML += newChar('bigChar')
    }
    spanEle.style.color = fontColor
    spanEle.style.transform = 'rotate(' + angle + 'deg)'
    spanEle.style.fontSize = fontSize
    spanEle.style.margin = marginNum + ' ' + (parseInt(marginNum) + 3) + 'px 0'
    tempNode.appendChild(spanEle)
    fontColor = ''
  }
}

// 生成随机字符
const newChar = (flag) => {
  let charEle = ''
  if (flag === 'num') {
    charEle = String(Math.floor(Math.random() * 10))
  } else if (flag === 'smallChar') {
    charEle = String.fromCharCode(Math.floor(Math.random() * 26) + 97)
  } else if (flag === 'bigChar') {
    charEle = String.fromCharCode(Math.floor(Math.random() * 26) + 97).toUpperCase()
  }
  code.value += charEle
  return charEle
}
</script>